#include "ElementSelectorList.h"
#include <QMimeData>
#include <QDrag>

ElementSelectorList::ElementSelectorList(QWidget * parent)
: QListWidget(parent), manager("/home/tfannes/kolonistenData/tiles.png")
{
	setDragEnabled(true);
	setViewMode(QListView::IconMode);
	setIconSize(manager.getTileSize());
	setSpacing(10);
	setAcceptDrops(true);
	setDropIndicatorShown(true);
}

ElementSelectorList::~ElementSelectorList()
{
}

void ElementSelectorList::initialize()
{
	board::TileData tile1;
	tile1.type = board::TileTypeSea;
	tile1.resource = board::TileResourceBrick;
	tile1.number = board::TileNumberUndefined;
	tile1.orientation = board::TileOrientation12H;

	addTile(tile1);

	tile1.type = board::TileTypeLand;
	tile1.resource = board::TileResourceWool;
	tile1.number = board::TileNumber10;
	tile1.orientation = board::TileOrientationUndefined;

	addTile(tile1);
}

void ElementSelectorList::addTile(const board::TileData & data)
{
	QListWidgetItem * tileItem = new QListWidgetItem(this);
	QByteArray outArray;
	QDataStream inStream(&outArray, QIODevice::WriteOnly);

	inStream << data;

	tileItem->setIcon(manager.getTilePixmap(data));
	tileItem->setData(Qt::UserRole, QVariant(outArray));
	tileItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
}

void ElementSelectorList::startDrag(Qt::DropActions /*supportedActions*/)
{
	QListWidgetItem * item = currentItem();

	QByteArray inArray = item->data(Qt::UserRole).toByteArray();
	QDataStream outStream(&inArray, QIODevice::ReadOnly);

	board::TileData data;
	outStream >> data;

	QByteArray itemData;
	QDataStream dataStream(&itemData, QIODevice::WriteOnly);
	dataStream << data;

	QMimeData * mimeData = new QMimeData();
	mimeData->setData("kolonisten/tile-item", itemData);

	QDrag * drag = new QDrag(this);
	drag->setMimeData(mimeData);
	drag->setPixmap(manager.getTilePixmap(data));
	drag->setHotSpot(QPoint(manager.getTileSize().width()/2,manager.getTileSize().height()/2));

	drag->exec(Qt::MoveAction);
}
